package com.doform.android.xianggucheng.activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.support.v7.app.AlertDialog;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.Spinner;
import android.widget.TextView;

import com.doform.android.xianggucheng.R;
import com.doform.android.xianggucheng.bean.Goods;
import com.doform.android.xianggucheng.bean.StarBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListArticleBean;
import com.doform.android.xianggucheng.bean.request_bean.ReqListStarBean;
import com.doform.android.xianggucheng.retrofit.ApiSpecTransformer.DialogTransformer;
import com.doform.android.xianggucheng.retrofit.HttpManager;
import com.doform.android.xianggucheng.retrofit.subscriber.ErrorHandleSubscriber;
import com.doform.android.xianggucheng.utils.Constans;
import com.doform.android.xianggucheng.widget.DividerItemDecoration;
import com.orhanobut.logger.Logger;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnLoadmoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.annotations.NonNull;

/**
 * Created by ph on 2017/5/11.
 */

public class ListArticleActivity extends BaseTitleActivity implements OnRefreshListener, OnLoadmoreListener {

    @BindView(R.id.progressBar)
    ProgressBar mProgressBar;

    @BindView(R.id.recyclerView)
    RecyclerView mRecyclerView;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;

    @BindView(R.id.tv_empty)
    TextView mEmpty;

    public static final int PAGE_CONTENT_INIT = 1;
    private int mCurrentPage = PAGE_CONTENT_INIT;

    @BindView(R.id.et_query)
    EditText et_query;

    private CommonAdapter mCommonAdapter;
    private List<Goods.ListBean> mGoodDatas = new ArrayList<>();
    private List<StarBean.ListBean> mStartDataList = new ArrayList<>();

    @Override
    protected int layoutResId() {
        return R.layout.activity_article_manager;
    }

    @Override
    protected void initView() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
    }

    @Override
    protected void initData() {
        getClienStartData();
    }

    /**
     * get the data from the server and update the UI
     */
    @Override
    protected void updateData() {
        super.updateData();
        refresh();
    }

    private void refresh() {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService(mCurrentPage);
    }


    @Override
    public void onRefresh(RefreshLayout refreshlayout) {
        mCurrentPage = PAGE_CONTENT_INIT;
        getDataForService2(mCurrentPage);
    }

    @Override
    public void onLoadmore(RefreshLayout refreshlayout) {
        mCurrentPage++;
        getDataForService2(mCurrentPage);
    }

    private void getClienStartData() {
        HttpManager.instance()
                .getStar2(new ReqListStarBean("1"))
                .subscribe(new ErrorHandleSubscriber<StarBean>() {
                    @Override
                    public void onNext(@NonNull StarBean starBean) {
                        parseStarData(starBean.getList());
                    }
                });
    }

    private void parseStarData(List<StarBean.ListBean> data) {
        mStartDataList.clear();
        mStartDataList.addAll(data);
    }

    @Override
    protected void initListener() {
        refreshLayout.setOnRefreshListener(this);
        refreshLayout.setOnLoadmoreListener(this);
        refreshLayout.setEnableHeaderTranslationContent(false);

        initAdater();
    }

    private void initAdater() {

        mCommonAdapter = new CommonAdapter<Goods.ListBean>(this, R.layout.activity_article_manager_item, mGoodDatas) {
            @Override
            protected void convert(ViewHolder holder, final Goods.ListBean articleBean, final int position) {

                TextView tv_name = holder.getView(R.id.tv_name);
                TextView tv_shops_name = holder.getView(R.id.tv_shops_name);
                TextView tv_inventory = holder.getView(R.id.tv_inventory);
                final TextView tv_cost = holder.getView(R.id.tv_cost);
                TextView tv_classify_name = holder.getView(R.id.tv_classify_name);
                ImageView ivIsUploadedPicture = holder.getView(R.id.iv_isUploadedPicture);

                if (TextUtils.isEmpty(articleBean.getImg())) {
                    ivIsUploadedPicture.setVisibility(View.INVISIBLE);
                } else {
                    ivIsUploadedPicture.setVisibility(View.VISIBLE);
                }
                tv_name.setText(articleBean.getName());
                tv_shops_name.setText(articleBean.getSuppliername());
                tv_classify_name.setText("分类：" + articleBean.getClslayernames());
                tv_inventory.setText(articleBean.getKunum());
                tv_cost.setText(articleBean.getBuyprice_det());

                holder.getView(R.id.tv_delete).setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        showDialog(articleBean, position);
                    }
                });

//                holder.getView(R.id.tv_edit_product).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        Intent intent = new Intent(ListArticleActivity.this, UpdateGoodsActivity.class);
//                        intent.putExtra(Constans.EXTRA_UPDATE_ARTICLE, mGoodDatas.get(position));
//                        startActivity(intent);
//                    }
//                });
//                holder.getView(R.id.tv_cost).setOnClickListener(new View.OnClickListener() {
//                    @Override
//                    public void onClick(View v) {
//                        showDialogEditPrice(articleBean, tv_cost);
//                    }
//                });

            }


        };
        mCommonAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                Intent intent = new Intent(ListArticleActivity.this, UpdateGoodsActivity.class);
                intent.putExtra(Constans.EXTRA_UPDATE_ARTICLE, mGoodDatas.get(position));
                startActivity(intent);
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mRecyclerView.setAdapter(mCommonAdapter);
    }


    private void postPriceDataToService(Goods.ListBean articleBean, String mStar, String mAddPriceType, String mAddPriceStr, String mPrice) {
        HttpManager.instance()
                .postUpdateArticlePrice();
    }


    private void showDialog(final Goods.ListBean articleBean, final int position) {
        new AlertDialog.Builder(this)
                .setMessage("该数据删除后将无法恢复，请确认是否要删除?")
                .setPositiveButton("确定",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                deleteItem(articleBean);
                            }
                        })
                .setNegativeButton("取消",
                        new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                            }
                        }).show();
    }

    private void deleteItem(final Goods.ListBean articleBean) {

        HttpManager.instance()
                .deleteArticle2(articleBean.getId(), articleBean.getGuid())
                .subscribe(new ErrorHandleSubscriber<Integer>() {
                    @Override
                    public void onNext(@NonNull Integer i) {
                        refresh();
                    }
                });
    }

    @Override
    protected void showView() {
        titleBar.setTextTitle("商品管理");
    }


    private void getDataForService(int pageid){
        getDataForService(pageid,"");
    }
    /**
     *
     * @param pageId
     * @param key
     */
    private void getDataForService(int pageId,String key) {
        HttpManager.instance()
                .getArticle2(new ReqListArticleBean(String.valueOf(pageId),key))
                .compose(new DialogTransformer<Goods>(mProgressBar))
                .subscribe(new ErrorHandleSubscriber<Goods>() {
                    @Override
                    public void onNext(@NonNull Goods goods) {
                        parseData(goods.getList());
                    }
                });
    }

    private void getDataForService2(int pageid){
        getDataForService2(pageid,"");
    }
    /**
     *
     * @param pageId
     * @param key
     */
    private void getDataForService2(int pageId,String key) {
        HttpManager.instance()
                .getArticle2(new ReqListArticleBean(String.valueOf(pageId),key))
                .subscribe(new ErrorHandleSubscriber<Goods>() {
                    @Override
                    public void onNext(@NonNull Goods goods) {
                        parseData(goods.getList());
                    }
                });
    }


    private void parseData(List<Goods.ListBean> data) {//解析从服务器获取的数据

        if (mCurrentPage == PAGE_CONTENT_INIT) {
            mGoodDatas.clear();
        }

        if (data.size() == 0 || data == null) {
            mCurrentPage--;
            refreshLayout.finishLoadmore();
            return;
        }
        mGoodDatas.addAll(data);
        mCommonAdapter.notifyDataSetChanged();
        refreshLayout.finishRefresh();
        refreshLayout.finishLoadmore();
    }

    @OnClick({R.id.btn_query, R.id.btn_add})
    public void click(View v) {
        switch (v.getId()) {
            case R.id.btn_query:
                String mQuery = et_query.getText().toString().trim();
                if (TextUtils.isEmpty(mQuery)) {
                    refresh();
                    return;
                }
                mCurrentPage = PAGE_CONTENT_INIT;
                getDataForService(mCurrentPage,mQuery);
                break;
            case R.id.btn_add:
                Intent intent = new Intent(this, NewGoodsActivity.class);
                startActivity(intent);
                break;
            default:
                break;
        }
    }


    private String mPrice = "";//价格
    private String mAddPriceStr = "";//加价值
    private String mAddPriceType = "";//加价类型

    private void showDialogEditPrice(final Goods.ListBean articleBean, final TextView tv_cost) {

        //初始化星级数据
        String[] stars = new String[mStartDataList.size()];
        for (int i = 0; i < mStartDataList.size(); i++) {
            stars[i] = mStartDataList.get(i).getName();
        }
//        初始化星级适配器
        final ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, stars);
        stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
//          初始化加价方式适配器
        String[] type = new String[]{"直接加", "百分比"};
        final ArrayAdapter<String> stringArrayAdapter2 = new ArrayAdapter<>(this, android.R.layout.simple_spinner_item, type);
        stringArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);


        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_price, null, false);
        final AlertDialog alertDialog = builder.setView(view).create();
        alertDialog.setCanceledOnTouchOutside(false);

        final Spinner mSpinnerAddPriceType = (Spinner) view.findViewById(R.id.spinner_add_price_type);
        mSpinnerAddPriceType.setAdapter(stringArrayAdapter2);

        final Spinner mSpinnerStarLevel = (Spinner) view.findViewById(R.id.spinner_star_level);
        mSpinnerStarLevel.setAdapter(stringArrayAdapter);

        final EditText etAddPriceValue = (EditText) view.findViewById(R.id.et_add_price_value);
        final EditText etPrice = (EditText) view.findViewById(R.id.et_price);

        Button btnSave = (Button) view.findViewById(R.id.btn_save);
        Button btnCancel = (Button) view.findViewById(R.id.btn_cancel);

        mAddPriceType = mSpinnerAddPriceType.getSelectedItem().toString().trim();
        etPrice.setText(articleBean.getBuyprice_det());

        alertDialog.show();

        final DecimalFormat df = new DecimalFormat("#.00");

        etAddPriceValue.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                Logger.v("输入文本之前的状态");

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                Logger.v("输入文字中的状态，count是一次性输入字符数");
            }

            @Override
            public void afterTextChanged(Editable s) {
                Logger.v("输入文字后的状态---" + s);

                mAddPriceStr = etAddPriceValue.getText().toString().trim();

                if (TextUtils.isEmpty(mAddPriceStr) || "".equals(mAddPriceStr)) {
                    mAddPriceStr = "0.00";
                }

                if ("百分比".equals(mAddPriceType)) {
                    float percent = Float.parseFloat(mAddPriceStr) / 100;
                    mPrice = df.format((Float.parseFloat(articleBean.getBuyprice_det()) * (1 + percent)));
                    etPrice.setText(mPrice);
                } else {
                    Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
                    Matcher match = pattern.matcher(mAddPriceStr);
                    if (match.matches()) {
                        float v = Float.parseFloat(mAddPriceStr);
                        mPrice = df.format(Float.parseFloat(articleBean.getCostprice()) + v);
                        etPrice.setText(mPrice);
                    } else {
                        etAddPriceValue.setError("请输入正确的金额数字");
                    }
                }
            }
        });
//        监测加价方式

        mSpinnerAddPriceType.setOnTouchListener(new View.OnTouchListener() {
                                                    @Override
                                                    public boolean onTouch(View v, MotionEvent event) {

                                                        if (mSpinnerAddPriceType.getSelectedItem().toString().trim().equals("百分比")) {
                                                            float percent = Float.parseFloat(mAddPriceStr) / 100;
                                                            mPrice = df.format((Float.parseFloat(articleBean.getBuyprice_det()) * (1 + percent)));
                                                            etPrice.setText(mPrice);
                                                        } else {
                                                            Pattern pattern = Pattern.compile("^(([1-9]{1}\\d*)|([0]{1}))(\\.(\\d){0,2})?$"); // 判断小数点后2位的数字的正则表达式
                                                            Matcher match = pattern.matcher(mAddPriceStr);
                                                            if (match.matches()) {
                                                                float price = Float.parseFloat(mAddPriceStr);
                                                                mPrice = df.format(Float.parseFloat(articleBean.getCostprice()) + price);
                                                                etPrice.setText(mPrice);
                                                            } else {
                                                                etAddPriceValue.setError("请输入正确的金额数字");
                                                            }
                                                        }

                                                        return false;
                                                    }
                                                }
        );

        btnCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        view.findViewById(R.id.tv_dialog_back).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                alertDialog.dismiss();
            }
        });
        btnSave.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                mPrice = etPrice.getText().toString().trim();
                mAddPriceStr = etAddPriceValue.getText().toString().trim();
                mAddPriceType = mSpinnerAddPriceType.getSelectedItem().toString().trim();
                String mStar = mSpinnerStarLevel.getSelectedItem().toString().trim();

                tv_cost.setText(etPrice.getText().toString());
                postPriceDataToService(articleBean, mStar, mAddPriceType, mAddPriceStr, mPrice);

                alertDialog.dismiss();
            }
        });

    }


}
